<template>
  <div
    class="app-container safe-area-inset-bottom">
    <NavBar v-if="showNavBar" safe-area-inset-top
      :title="(currentRouteTitle as string)"
      :left-arrow="(showBackButton as boolean)"
      @click-left="handleBack" />

    <main
      :class="['main-content', { 'expend-main': showFooter }]">
      <RouterView v-if="!loading" />
    </main>

    <Tabbar v-model="activeTab" v-if="showFooter" route>
      <TabbarItem v-for="tab in tabs"
        :key="tab.path" :to="tab.path"
        :icon="tab.icon">
        {{ tab.title }}
      </TabbarItem>
    </Tabbar>
  </div>
</template>
<script setup lang="ts">
import { storeToRefs } from 'pinia';
import {
  NavBar, Tabbar, TabbarItem,
} from 'vant';
import {
  computed, onMounted, ref,
} from 'vue';
import { RouterView, useRoute, useRouter } from 'vue-router';

import useAuthStore from '@/stores/auth.store';

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const { roles, permissions } = storeToRefs(authStore);

// 底部导航配置
const tabs = computed(() => [
  {
    path: '/home',
    title: '消息',
    icon: 'home-o',
  },
  {
    path: '/friend',
    title: '联系人',
    icon: 'balance-pay',
  },
  {
    path: '/mine',
    title: '我的',
    icon: 'user-o',
  },
].filter((i: any) => {
  if (!i.roles && !i.permissions) {
    return true;
  }
  if (i.roles) {
    return i.roles.some((role: string) => roles.value.includes(role));
  }
  if (i.permissions) {
    return i.permissions.some((permission: string) => permissions.value.includes(permission));
  }
  return false;
}));

const showNavBar = computed(() => !route.meta.hideNavBar);
const showBackButton = computed(() => route.meta.requiresBack);
const currentRouteTitle = computed(() => route.meta.title || '卡券回收平台');
const showFooter = computed(() => !route.meta.hideFooter);
const prevRoute = computed(
  () => router.options.history.state.back || { name: 'Profile' },
);

const activeTab = ref(0);
const loading = ref(false);

onMounted(() => {
});

router.afterEach((to) => {
  const index = tabs.value.findIndex((tab) => tab.path === to.path);
  activeTab.value = index >= 0 ? index : 0;
  document.title = (to.meta.title as string) || '卡券回收平台';
});

const handleBack = () => router.push(prevRoute.value as any);
</script>
<style lang="less" scoped>
.app-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  margin: 0 auto;

  .main-content {
    height: 100%;
    background-color: var(--van-background-2);
    flex-grow: 1;
  }
}
</style>
